package tech.aistar.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 本类用来演示: 日期工具类
 *
 * @author: success
 * @date: 2022/7/20 8:56 上午
 */
public class DateUtil {

    public static boolean isLeapYear(int year){
        //if((year%4==0 && year%100!=0) || year%400==0)
        //    return true;
        //return false;
        return (year%4==0 && year%100!=0) || year%400==0;
    }

    public static int getMaxDays(int year,int month){
        if(month<1 || month>12)
            return -1;//错误的提示
        int days = 0;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days=31;
                break;
            case 2:
                //days=28;
                //if(isLeapYear(year))
                //    days++;
                days = isLeapYear(year)?29:28;
                break;
            default:
                days = 30;
                break;
        }
        return days;
    }

    /**
     * 某年某月某日是周几
     * @param year
     * @param month
     * @param date
     * @return
     */
    public static int getDayOfWeek(int year,int month,int date){
        Calendar cal = Calendar.getInstance();
        cal.set(year,month-1,date);

        return cal.get(Calendar.DAY_OF_WEEK)-1;//周日是数字0
    }

    public static String format(Date date,String pattern){
        if(null == date)
            return null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        return sdf.format(date);
    }

    public static Date parse(String sdate,String pattern)  {
        if(null == sdate || sdate.trim().length()==0)
            return null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = null;
        //springmvc/springboot - 全局异常处理器 => 异常
        try {
            date = sdf.parse(sdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    //public static void main(String[] args) {
    //
    //    Date date = parse("2022-02-09","yyyy-MM-dd");
    //
    //}

    public static Date createDate(int year,int month,int date){
        Calendar cal = Calendar.getInstance();
        cal.set(year,month-1,date);

        return cal.getTime();
    }
}
